package qsoft.omanga.base.sao;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * 
 * @author sontt
 *
 */
public class ServiceHelper {
    /**
     * @author Sontt
     * @param strURL
     *            (String)
     * @category get file XML from URL
     * @return document XML
     */
    public Document getXMLDoc(String strURL) {
        Document doc = null;
        try {
            URL url = new URL(strURL);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(is);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return doc;
    }

    /**
     * @author Sontt
     * @param strURL
     *            String
     * @param defaultHandler
     *            DefaultHandler
     */
    public void parseXMLSAX(String strURL, DefaultHandler defaultHandler) {
        try {
            URL url = new URL(strURL);
            URLConnection conn = url.openConnection();
            InputStream is = conn.getInputStream();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(is, defaultHandler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
